import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入全局的样式
import '../assets/css/global.css'
// 引入字体图标
import '../assets/fonts/iconfont.css'
// 导入登录页面组件
import Login from '../components/Login.vue'
// 导入Home组件
import Home from '../components/Home.vue'
// 导入Welcome组件
import Welcome from '../components/Welcome.vue'
// 导入用户列表组件
import Users from '../components/user/Users.vue'
// 导入权限管理组件
import Rights from '../components/power/Rights.vue'
// 导入角色列表组件
import Roles from '../components/power/Roles.vue'
// 导入商品分类组件
import Cate from '../components/goods/Cate.vue'
// 引入参数组件
import Params from '../components/goods/Params.vue'
// 导入商品列表组件
import List from '../components/goods/List.vue'
// 导入添加商品组件
import AddGoods from '../components/goods/Add.vue'
// 导入订单组件
import Order from '../components/order/Order.vue'
// 导入报表组件
import Report from '../components/report/Report.vue'

Vue.use(VueRouter)

// 定义路由规则
const router = new VueRouter({
  routes: [{ path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    { path: '/home', component: Home, redirect: '/welcome', children: [
      { path: '/welcome', component: Welcome },
      { path: '/users', component: Users },
      { path: '/rights', component: Rights },
      { path: '/roles', component: Roles },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: List },
      { path: '/goods/add', component: AddGoods },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ] }
  ]
})

// 设置路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从哪里跳转过来的
  // next 是一个函数表示放行
  // 1.next() 代表放行
  // 2.next('/login') 代表强制跳转到哪个路径
  // 访问登录页直接放行
  if (to.path === '/login') return next()
  // 获取 token
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果 token 为空就 继续跳到 /login
  if (!tokenStr) return next('/login')
  // 如果 token 存在直接跳转下个页面
  next()
})

export default router
